import { useState, useEffect } from 'react';
import { Breadcrumb, Popconfirm, Divider } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { Link, useLocation, useNavigate } from 'umi';

// 面包屑项类型定义
interface BreadcrumbItem {
  path: string;
  name: string;
}

const ClosableBreadcrumb = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [items, setItems] = useState<BreadcrumbItem[]>([]);

  // 递归遍历路由数据（含子路由），构建路径与locale的映射
  const buildPathNameMap = (routes: any[], parentPath = '') => {
    const map: Record<string, string> = {};

    routes.forEach((item) => {
      const fullPath = parentPath ? `${parentPath}/${item.path}` : item.path;
      if (item.meta && item.meta.locale) {
        map[fullPath] = item.meta.locale;
      }
      // 递归处理子路由
      if (item.children && item.children.length > 0) {
        Object.assign(map, buildPathNameMap(item.children, fullPath));
      }
    });

    return map;
  };

  // 从本地存储获取路由数据并构建映射
  const getPathNameMap = () => {
    const menuStr = localStorage.getItem('menu');
    if (!menuStr) return {};

    const menu = JSON.parse(menuStr);
    return buildPathNameMap(menu);
  };

  const pathNameMap = getPathNameMap();

  // 从当前路径解析面包屑项
  useEffect(() => {
    const pathSegments = location.pathname.split('/').filter(Boolean);
    const newItems: BreadcrumbItem[] = [];

    // 解析路径段
    let currentPath = '';
    pathSegments.forEach((segment) => {
      currentPath += `/${segment}`;
      // 从映射中获取locale名称，若没有则用路径段首字母大写
      const name = pathNameMap[currentPath] || segment.charAt(0).toUpperCase() + segment.slice(1);
      newItems.push({
        path: currentPath,
        name: name,
      });
    });

    setItems(newItems);
  }, [location.pathname]);

  // 处理关闭事件
  const handleClose = (index: number) => {
    // 不能关闭最后一项和首页
    if (index === items.length - 1 || index === 0) return;

    // 获取要跳转的路径
    const targetPath = items[index - 1].path;
    navigate(targetPath);
  };

  return (
    <Breadcrumb separator={<Divider type="vertical" style={{ margin: '0 8px' }} />}>
      {items.map((item, index) => (
        <Breadcrumb.Item key={item.path} className="breadcrumb-item">
          {index < items.length - 1 ? (
            <Link to={item.path}>{item.name}</Link>
          ) : (
            <span>{item.name}</span> // 当前页不添加链接
          )}

          {/* 不是首页且不是最后一项时显示关闭按钮 */}
          {index !== 0 && index < items.length - 1 && (
            <Popconfirm
              title="确定要移除该路径吗？"
              onConfirm={() => handleClose(index)}
              okText="是"
              cancelText="否"
              placement="bottom"
            >
              <CloseOutlined
                style={{
                  marginLeft: 4,
                  cursor: 'pointer',
                  fontSize: '12px',
                  color: '#999',
                }}
              />
            </Popconfirm>
          )}
        </Breadcrumb.Item>
      ))}
    </Breadcrumb>
  );
};

export default ClosableBreadcrumb;